<template>
  <a-modal
    v-model:visible="modalVisible"
    @ok="handleOk"
    @cancel="handleCancel"
    :width="800"
    unmount-on-close
    :maskClosable="false"
    :on-before-ok="onBeforeOk"
  >
    <template #title> 设置评分人 </template>
    <template v-if="!props.type">
      <div>启用评分类别</div>
      <div class="item">
        <div>指定员工</div>
        <a-switch
          v-model="formData.scorerStatus.appoint.status"
          :checked-value="1"
          :unchecked-value="2"
          @change="change($event, 1)"
        />
      </div>
      <div class="item">
        <div>上级</div>
        <a-switch
          v-model="formData.scorerStatus.superiors.status"
          :checked-value="1"
          :unchecked-value="2"
          @change="change($event, 2)"
        />
      </div>
      <div class="item">
        <div>同级</div>
        <a-switch
          v-model="formData.scorerStatus.peer.status"
          :checked-value="1"
          :unchecked-value="2"
          @change="change($event, 3)"
        />
      </div>
      <div class="item">
        <div>下属</div>
        <a-switch
          v-model="formData.scorerStatus.junior.status"
          :checked-value="1"
          :unchecked-value="2"
          @change="change($event, 4)"
        />
      </div>
      <div class="item">
        <div>其他</div>
        <a-switch
          v-model="formData.scorerStatus.other.status"
          :checked-value="1"
          :unchecked-value="2"
          @change="change($event, 6)"
        />
      </div>

      <div class="table-div">
        <div class="tr">
          <div class="td">类别</div>
          <div class="td">层级权重</div>
          <div class="td">员工</div>
          <div class="td">启用他人代办</div>
          <div class="td">权重</div>
          <div class="td">操作</div>
        </div>
        <div class="tr" v-if="formData.scorerStatus.appoint.status === 1">
          <div class="td td1">指定员工</div>
          <div class="td td2">
            <a-input-number
              v-model="formData.scorerStatus.appoint.weight"
              hide-button
              style="width: 100px"
            >
              <template #suffix> % </template>
            </a-input-number>
          </div>
          <div class="td td3">
            <div
              class="human"
              v-for="(item, index) in formData.scorer"
              :key="index"
            >
              <template v-if="item.type === 1">
                <div class="td">{{ item.userName }}</div>
                <div class="td">
                  <a-switch
                    v-model="item.isWaitDone"
                    :checked-value="1"
                    :unchecked-value="2"
                  />
                </div>
                <div class="td">
                  <a-input-number
                    v-model="item.weight"
                    hide-button
                    style="width: 100px"
                  >
                    <template #suffix> % </template>
                  </a-input-number>
                </div>
                <div class="td">
                  <a-tooltip content="删除" position="left">
                    <a-popconfirm
                      content="是否确认删除该条数据?"
                      @ok="remove(index, item.id)"
                    >
                      <IconFont
                        type="icon-delete"
                        :size="26"
                        :style="{
                          marginRight: '10px',
                          cursor: 'pointer'
                        }"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </div>
              </template>
            </div>
            <div class="human">
              <div class="td">
                <a-button @click="addHuman(1)">新增员工</a-button>
              </div>
              <div class="td"></div>
              <div class="td"></div>
              <div class="td"></div>
            </div>
          </div>
        </div>
        <div class="tr" v-if="formData.scorerStatus?.superiors.status === 1">
          <div class="td td1">上级</div>
          <div class="td td2">
            <a-input-number
              v-model="formData.scorerStatus.superiors.weight"
              hide-button
              style="width: 100px"
            >
              <template #suffix> % </template>
            </a-input-number>
          </div>
          <div class="td td3">
            <div
              class="human"
              v-for="(item, index) in formData.scorer"
              :key="index"
            >
              <template v-if="item.type === 2">
                <div class="td">
                  {{ item.userName }}
                </div>
                <div class="td">
                  <a-switch
                    v-model="item.isWaitDone"
                    :checked-value="1"
                    :unchecked-value="2"
                  />
                </div>
                <div class="td">
                  <a-input-number
                    v-model="item.weight"
                    hide-button
                    style="width: 100px"
                  >
                    <template #suffix> % </template>
                  </a-input-number>
                </div>
                <div class="td">
                  <a-tooltip content="删除" position="left">
                    <a-popconfirm
                      content="是否确认删除该条数据?"
                      @ok="remove(index, item.id)"
                    >
                      <IconFont
                        type="icon-delete"
                        :size="26"
                        :style="{
                          marginRight: '10px',
                          cursor: 'pointer'
                        }"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </div>
              </template>
            </div>
            <div class="human">
              <div class="td">
                <a-button @click="addHuman(2)">新增员工</a-button>
              </div>
              <div class="td"></div>
              <div class="td"></div>
              <div class="td"></div>
            </div>
          </div>
        </div>
        <div class="tr" v-if="formData.scorerStatus?.peer.status === 1">
          <div class="td td1">同级</div>
          <div class="td td2">
            <a-input-number
              v-model="formData.scorerStatus.peer.weight"
              hide-button
              style="width: 100px"
            >
              <template #suffix> % </template>
            </a-input-number>
          </div>
          <div class="td td3">
            <div
              class="human"
              v-for="(item, index) in formData.scorer"
              :key="index"
            >
              <template v-if="item.type === 3">
                <div class="td">
                  {{ item.userName }}
                </div>
                <div class="td">
                  <a-switch
                    v-model="item.isWaitDone"
                    :checked-value="1"
                    :unchecked-value="2"
                  />
                </div>
                <div class="td">
                  <a-input-number
                    v-model="item.weight"
                    hide-button
                    style="width: 100px"
                  >
                    <template #suffix> % </template>
                  </a-input-number>
                </div>
                <div class="td">
                  <a-tooltip content="删除" position="left">
                    <a-popconfirm
                      content="是否确认删除该条数据?"
                      @ok="remove(index, item.id)"
                    >
                      <IconFont
                        type="icon-delete"
                        :size="26"
                        :style="{
                          marginRight: '10px',
                          cursor: 'pointer'
                        }"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </div>
              </template>
            </div>
            <div class="human">
              <div class="td">
                <a-button @click="addHuman(3)">新增员工</a-button>
              </div>
              <div class="td"></div>
              <div class="td"></div>
              <div class="td"></div>
            </div>
          </div>
        </div>
        <div class="tr" v-if="formData.scorerStatus?.junior.status === 1">
          <div class="td td1">下属</div>
          <div class="td td2">
            <a-input-number
              v-model="formData.scorerStatus.junior.weight"
              hide-button
              style="width: 100px"
            >
              <template #suffix> % </template>
            </a-input-number>
          </div>
          <div class="td td3">
            <div
              class="human"
              v-for="(item, index) in formData.scorer"
              :key="index"
            >
              <template v-if="item.type === 4">
                <div class="td">
                  {{ item.userName }}
                </div>
                <div class="td">
                  <a-switch
                    v-model="item.isWaitDone"
                    :checked-value="1"
                    :unchecked-value="2"
                  />
                </div>
                <div class="td">
                  <a-input-number
                    v-model="item.weight"
                    hide-button
                    style="width: 100px"
                  >
                    <template #suffix> % </template>
                  </a-input-number>
                </div>
                <div class="td">
                  <a-tooltip content="删除" position="left">
                    <a-popconfirm
                      content="是否确认删除该条数据?"
                      @ok="remove(index, item.id)"
                    >
                      <IconFont
                        type="icon-delete"
                        :size="26"
                        :style="{
                          marginRight: '10px',
                          cursor: 'pointer'
                        }"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </div>
              </template>
            </div>
            <div class="human">
              <div class="td">
                <a-button @click="addHuman(4)">新增员工</a-button>
              </div>
              <div class="td"></div>
              <div class="td"></div>
              <div class="td"></div>
            </div>
          </div>
        </div>
        <div class="tr" v-if="formData.scorerStatus?.other.status === 1">
          <div class="td td1">其他</div>
          <div class="td td2">
            <a-input-number
              v-model="formData.scorerStatus.other.weight"
              hide-button
              style="width: 100px"
            >
              <template #suffix> % </template>
            </a-input-number>
          </div>
          <div class="td td3">
            <div
              class="human"
              v-for="(item, index) in formData.scorer"
              :key="index"
            >
              <template v-if="item.type === 6">
                <div class="td">
                  {{ item.userName }}
                </div>
                <div class="td">
                  <a-switch
                    v-model="item.isWaitDone"
                    :checked-value="1"
                    :unchecked-value="2"
                  />
                </div>
                <div class="td">
                  <a-input-number
                    v-model="item.weight"
                    hide-button
                    style="width: 100px"
                  >
                    <template #suffix> % </template>
                  </a-input-number>
                </div>
                <div class="td">
                  <a-tooltip content="删除" position="left">
                    <a-popconfirm
                      content="是否确认删除该条数据?"
                      @ok="remove(index, item.id)"
                    >
                      <IconFont
                        type="icon-delete"
                        :size="26"
                        :style="{
                          marginRight: '10px',
                          cursor: 'pointer'
                        }"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </div>
              </template>
            </div>
            <div class="human">
              <div class="td">
                <a-button @click="addHuman(6)">新增员工</a-button>
              </div>
              <div class="td"></div>
              <div class="td"></div>
              <div class="td"></div>
            </div>
          </div>
        </div>
      </div>
    </template>
    <template v-else>
      <div class="table-div">
        <div class="tr">
          <div class="td">员工</div>
          <div class="td">启用他人代办</div>
          <div class="td">权重</div>
          <div class="td">操作</div>
        </div>
        <div class="tr">
          <div class="td td3">
            <div
              class="human"
              v-for="(item, index) in formData.scorer"
              :key="index"
            >
              <template v-if="item.type !== 5">
                <div class="td">{{ item.userName }}</div>
                <div class="td">
                  <a-switch
                    v-model="item.isWaitDone"
                    :checked-value="1"
                    :unchecked-value="2"
                  />
                </div>
                <div class="td">
                  <a-input-number
                    v-model="item.weight"
                    hide-button
                    style="width: 100px"
                  >
                    <template #suffix> % </template>
                  </a-input-number>
                </div>
                <div class="td">
                  <a-tooltip content="删除" position="left">
                    <a-popconfirm
                      content="是否确认删除该条数据?"
                      @ok="remove(index, item.id)"
                    >
                      <IconFont
                        type="icon-delete"
                        :size="26"
                        :style="{
                          marginRight: '10px',
                          cursor: 'pointer'
                        }"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </div>
              </template>
            </div>
            <div class="human">
              <div class="td">
                <a-button @click="addHuman(1)">新增员工</a-button>
              </div>
              <div class="td"></div>
              <div class="td"></div>
              <div class="td"></div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </a-modal>
  <HumanModal
    v-model:visible="humanModalVisible"
    :data="currentHumanList"
    @submit="submit"
  />
</template>
<script setup lang="ts">
import { PersonnelAbilityQualityIndexLibrary } from '@/apis/human/base/variationManager/probation/type';
import { useVModel } from '@vueuse/core';
import { delScoreHuman } from '@/apis/human/base/variationManager/probation';
import HumanModal from './HumanMadal/index.vue';
import { cloneDeep } from 'lodash';
import { Message } from '@arco-design/web-vue';
import allocationWeight from '@/utils/probation';

const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    data: PersonnelAbilityQualityIndexLibrary; // 传进来的数据,
    /**
     * 是否显示上下级,默认0显示，1不显示
     */
    type?: number;
    /**
     * 1能力素质指标 2加减分项指标 3关键业绩指标 4否决指标 5工作计划指标库 6 目标指标
     */
    indexType: number;
    delIds?: number[];
  }>(),
  {
    delIds: () => [],
    type: 0
  }
);

const emit = defineEmits([
  'update:visible',
  'update:data',
  'save',
  'del',
  'update:delIds'
]);
const modalVisible = useVModel(props, 'visible', emit);
const formData = useVModel(props, 'data', emit);
const modelDelIds = useVModel(props, 'delIds', emit);

const handleOk = () => {
  modelDelIds.value = [
    ...(modelDelIds.value || []),
    ...(delScorerIds.value || [])
  ];
  emit('save');
  emit('update:visible', false);
};
const validate = () => {
  if (!props.type) {
    let gradeWeight = 0; //层级权重的和
    const { scorerStatus, scorer } = formData.value;

    if (scorerStatus?.appoint?.status === 1) {
      const { weight } = scorerStatus.appoint;
      gradeWeight += weight ? weight : 0;
      const scorerWeightTotal = scorer?.reduce(
        (previousValue, currentValue) => {
          //层级下所有员工评分权重的和
          let scorerWieght = currentValue.weight ? currentValue.weight : 0;
          scorerWieght = currentValue.type === 1 ? scorerWieght : 0;
          if (currentValue.type === 5) scorerWieght = 0;
          return previousValue + scorerWieght;
        },
        0
      );
      if (scorerWeightTotal && scorerWeightTotal !== 100) {
        Message.error('指定员工评分权重的和必须等于100。');
        return '指定员工评分权重的和必须等于100。';
      }
    }
    if (scorerStatus?.peer?.status === 1) {
      const { weight } = scorerStatus.peer;
      gradeWeight += weight ? weight : 0;
      const scorerWeightTotal = scorer?.reduce(
        (previousValue, currentValue) => {
          let scorerWieght = currentValue.weight ? currentValue.weight : 0;
          scorerWieght = currentValue.type === 4 ? scorerWieght : 0;
          return previousValue + scorerWieght;
        },
        0
      );
      if (scorerWeightTotal && scorerWeightTotal !== 100) {
        Message.error('同级员工评分权重的和必须等于100。');
        return '同级员工评分权重的和必须等于100。';
      }
    }
    if (scorerStatus?.superiors?.status === 1) {
      const { weight } = scorerStatus.superiors;
      gradeWeight += weight ? weight : 0;
      const scorerWeightTotal = scorer?.reduce(
        (previousValue, currentValue) => {
          let scorerWieght = currentValue.weight ? currentValue.weight : 0;
          scorerWieght = currentValue.type === 2 ? scorerWieght : 0;
          return previousValue + scorerWieght;
        },
        0
      );
      if (scorerWeightTotal && scorerWeightTotal !== 100) {
        Message.error('上级员工评分权重的和必须等于100。');
        return '上级员工评分权重的和必须等于100。';
      }
    }
    if (scorerStatus?.junior?.status === 1) {
      const { weight } = scorerStatus.junior;
      gradeWeight += weight ? weight : 0;
      const scorerWeightTotal = scorer?.reduce(
        (previousValue, currentValue) => {
          let scorerWieght = currentValue.weight ? currentValue.weight : 0;
          scorerWieght = currentValue.type === 3 ? scorerWieght : 0;
          return previousValue + scorerWieght;
        },
        0
      );
      if (scorerWeightTotal && scorerWeightTotal !== 100) {
        Message.error('下级员工评分权重的和必须等于100。');
        return '下级员工评分权重的和必须等于100。';
      }
    }
    if (scorerStatus?.other?.status === 1) {
      const { weight } = scorerStatus.other;
      gradeWeight += weight ? weight : 0;
      const scorerWeightTotal = scorer?.reduce(
        (previousValue, currentValue) => {
          let scorerWieght = currentValue.weight ? currentValue.weight : 0;
          scorerWieght = currentValue.type === 6 ? scorerWieght : 0;
          return previousValue + scorerWieght;
        },
        0
      );
      if (scorerWeightTotal && scorerWeightTotal !== 100) {
        Message.error('其他员工评分权重的和必须等于100。');
        return '其他员工评分权重的和必须等于100。';
      }
    }
    if (gradeWeight !== 100) {
      Message.error('层级权重的和必须等于100.');
      return '层级权重的和必须等于100.';
    }
  } else {
    const { scorer } = formData.value;
    //编辑时需要忽略自评
    const scorerWeightTotal = scorer?.reduce((previousValue, currentValue) => {
      let scorerWieght = currentValue.weight ? currentValue.weight : 0;
      if (currentValue.type === 5) scorerWieght = 0;
      return previousValue + scorerWieght;
    }, 0);
    if (scorerWeightTotal !== 100) {
      Message.error('员工评分权重的和必须等于100。');
      return '员工评分权重的和必须等于100。';
    }
  }
  return;
};
const delScorerIds = ref<number[]>([]);
const handleCancel = () => {
  delScorerIds.value = [];

  emit('update:visible', false);
};
const remove = async (index: number, id?: number) => {
  if (!formData.value.scorer) return;
  try {
    if (id) {
      delScorerIds.value.push(id);
      // await delScoreHuman({ ids: [id], type: props.indexType });
      formData.value.scorer.splice(index, 1);
    } else formData.value.scorer.splice(index, 1);
  } catch (error: unknown) {
    console.log(error);
  }
  if (!formData.value.scorer?.length) return;
  formData.value.scorer = allocationWeight(formData.value.scorer);
  // emit('del');
};
const change = (ev: any, type: number) => {
  switch (type) {
    case 1:
      if (ev !== 1) {
        const delScorer = formData.value.scorer?.filter(
          (item) => item.type === type
        );
        const ids = delScorer?.map((item) => item.id);
        if (ids?.length) {
          delScorerIds.value = [...(delScorerIds.value || []), ...(ids || [])];
        }
        formData.value.scorerStatus.appoint.weight = 0;
        formData.value.scorer = formData.value.scorer?.filter(
          (item) => item.type !== type
        );
      } else {
        formData.value.scorerStatus.appoint.weight = 0;
        if (!Array.isArray(formData.value.scorer)) {
          formData.value.scorer = [];
        }
      }
      break;
    case 2:
      if (ev !== 1) {
        const delScorer = formData.value.scorer?.filter(
          (item) => item.type === type
        );
        const ids = delScorer?.map((item) => item.id);
        if (ids?.length) {
          delScorerIds.value = [...(delScorerIds.value || []), ...(ids || [])];
        }
        formData.value.scorerStatus.superiors.weight = 0;
        formData.value.scorer = formData.value.scorer?.filter(
          (item) => item.type !== type
        );
      } else {
        formData.value.scorerStatus.superiors.weight = 0;
        if (!Array.isArray(formData.value.scorer)) {
          formData.value.scorer = [];
        }
      }
      break;

    case 3:
      if (ev !== 1) {
        const delScorer = formData.value.scorer?.filter(
          (item) => item.type === type
        );
        const ids = delScorer?.map((item) => item.id);
        if (ids?.length) {
          delScorerIds.value = [...(delScorerIds.value || []), ...(ids || [])];
        }
        formData.value.scorerStatus.peer.weight = 0;
        formData.value.scorer = formData.value.scorer?.filter(
          (item) => item.type !== type
        );
      } else {
        formData.value.scorerStatus.peer.weight = 0;
        if (!Array.isArray(formData.value.scorer)) {
          formData.value.scorer = [];
        }
      }
      break;

    case 4:
      if (ev !== 1) {
        const delScorer = formData.value.scorer?.filter(
          (item) => item.type === type
        );
        const ids = delScorer?.map((item) => item.id);
        if (ids?.length) {
          delScorerIds.value = [...(delScorerIds.value || []), ...(ids || [])];
        }
        formData.value.scorerStatus.junior.weight = 0;
        formData.value.scorer = formData.value.scorer?.filter(
          (item) => item.type !== type
        );
      } else {
        formData.value.scorerStatus.junior.weight = 0;
        if (!Array.isArray(formData.value.scorer)) {
          formData.value.scorer = [];
        }
      }
      break;

    case 6:
      if (ev !== 1) {
        const delScorer = formData.value.scorer?.filter(
          (item) => item.type === type
        );
        const ids = delScorer?.map((item) => item.id);
        if (ids?.length) {
          delScorerIds.value = [...(delScorerIds.value || []), ...(ids || [])];
        }
        formData.value.scorerStatus.other.weight = 0;
        formData.value.scorer = formData.value.scorer?.filter(
          (item) => item.type !== type
        );
      } else {
        formData.value.scorerStatus.other.weight = 0;
        if (!Array.isArray(formData.value.scorer)) {
          formData.value.scorer = [];
        }
      }
      break;
  }
  // 统计开启的类型，平均权重
  let count = 0;
  if (formData.value.scorerStatus.appoint?.status === 1) {
    count += 1;
  }
  if (formData.value.scorerStatus.superiors?.status === 1) {
    count += 1;
  }
  if (formData.value.scorerStatus.peer?.status === 1) {
    count += 1;
  }
  if (formData.value.scorerStatus.junior?.status === 1) {
    count += 1;
  }
  if (formData.value.scorerStatus.other?.status === 1) {
    count += 1;
  }
  if (!count) return;
  const quotient = Math.floor(100 / count);
  const remainder = 100 % count;
  if (formData.value.scorerStatus.appoint.status === 1) {
    formData.value.scorerStatus.appoint.weight = quotient + remainder;
  }
  if (formData.value.scorerStatus.superiors.status === 1) {
    formData.value.scorerStatus.superiors.weight = quotient;
  }
  if (formData.value.scorerStatus.peer.status === 1) {
    formData.value.scorerStatus.peer.weight = quotient;
  }
  if (formData.value.scorerStatus.junior.status === 1) {
    formData.value.scorerStatus.junior.weight = quotient;
  }
  if (formData.value.scorerStatus.other.status === 1) {
    formData.value.scorerStatus.other.weight = quotient;
  }
};
const humanModalVisible = ref(false);
const currentHumanList = ref<any[]>([]);
const currenType = ref(0);
const addHuman = (n: number) => {
  currenType.value = n;
  const res = formData.value.scorer?.filter((item) => item.type === 1);
  currentHumanList.value = cloneDeep(res) || [];
  humanModalVisible.value = true;
};
// 新增评分人及分配权重
const submit = () => {
  currentHumanList.value.forEach((item) => {
    const { id, name } = item;
    if (!Array.isArray(formData.value.scorer)) {
      formData.value.scorer = [];
    }
    formData.value.scorer.push({
      userName: name,
      userId: id,
      isWaitDone: 2,
      weight: 0,
      type: currenType.value
    });
  });
  if (!formData.value.scorer?.length) return;
  formData.value.scorer = allocationWeight(formData.value.scorer);
};
const onBeforeOk = () => {
  const check = validate();
  if (check) return false;
  return true;
};
// 分配权重
// const allocationWeight = () => {
//   const scorerList = formData.value.scorer?.filter((item) => item.type === 1);
//   if (!scorerList?.length) return;
//   const scorerCount = scorerList?.length;
//   const quotient = Math.floor(100 / scorerCount);
//   const remainder = 100 % scorerCount;
//   scorerList.forEach((item, index) => {
//     item.weight = index ? quotient : quotient + remainder;
//   });
// };
</script>
<style lang="less" scoped>
.item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
  height: 30px;
  margin: 10px 0;
}
.table-div {
  display: flex;
  flex-direction: column;
  width: 100%;
}
.tr {
  display: flex;
  min-height: 60px;
  width: 100%;
  border-top: 1px solid #e5e6eb;
  border-left: 1px solid #e5e6eb;
}
.td {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  border-bottom: 1px solid #e5e6eb;
  border-right: 1px solid #e5e6eb;
}
.td1 {
  flex: 1;
}
.td2 {
  flex: 1;
}
.td3 {
  flex: 4;
  flex-direction: column;
}
.human {
  width: 100%;
  display: flex;
  // align-items: center;
  .td {
    min-height: 60px;
  }
}
</style>
